package com.permission.controller;

import com.permission.enumeration.PerResourceType;
import com.permission.model.PerResource;
import com.permission.service.PerResourceService;
import com.permission.util.BizConstants;
import com.solution.framework.controller.BaseController;
import com.solution.framework.util.*;
import com.spring.security.MySecurityConstants;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with generator tools.
 * User: sunguangzhu
 * DateTime:2014-04-28 04:08:30
 */

@Controller
public class PerResourceController extends BaseController<PerResource> {

    private static final String path_index = "perResource/perResource_index";
    private static final String path_input_menu = "perResource/perResourceMenu_input";
    private static final String path_input_operate = "perResource/perResourceOperate_input";
    private static final String path_view_menu = "perResource/perResourceMenu_view";
    private static final String path_view_operate = "perResource/perResourceOperate_view";
    private static final String path_search = "perResource/perResource_search";

    @Resource
    private PerResourceService perResourceService;

    @RequestMapping
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("index method ....");
        return path_index;
    }

    @Override
    protected List<Criterion> getSearchCriterions(HttpServletRequest request) {
        //用hibernate提供的类
        //simple search
        String search_type = RequestVarsUtil.getString(request, "search_type");
        List<Criterion> criterions = new ArrayList<Criterion>();
        if (StringUtils.isNotBlank(search_type)) {
            if (search_type.equals(Constant.SIMPLE_SEARCH_TYPE)) {
                String param = RequestVarsUtil.getString(request, "param");
                String value = RequestVarsUtil.getString(request, "value");
                if (StringUtils.isNotBlank(value)) {
                    if (param.equals("all")) {
                        //模糊查询所有字段
                        criterions.add(Restrictions.or(Restrictions.like("propStr", "%" + value + "%"), Restrictions.like("description", "%" + value + "%")));
                    } else {
                        //查询指定字段
                        criterions.add(Restrictions.like(param, "%" + value + "%"));
                    }
                }
            } else {
                //高级查询
                String name = RequestVarsUtil.getString(request, "name");
                criterions.add(Restrictions.eq("name", name));
            }
        }
        //other search
        Long nodeId = RequestVarsUtil.getLong(request, "nodeId");
        if (nodeId.longValue() != 0l) {
            criterions.add(Restrictions.eq("parent.id", nodeId));
        }
        criterions.add(Restrictions.eq("type", PerResourceType.OPERATE.getValue()));
        return criterions;    //To change body of overridden methods use File | Settings | File Templates.
    }

    @ResponseBody
    @RequestMapping
    protected void getGridData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Pagination pagination = RequestVarsUtil.getPagination(request);
        List<Criterion> criterions = this.getSearchCriterions(request);
        List<PerResource> entitys = this.perResourceService.listByCriteria(pagination, criterions);
        int total = this.perResourceService.getTotalByCriteria(criterions);
        ResultDto<List<PerResource>> resultDto = new ResultDto<List<PerResource>>(entitys, total);
        System.out.println(" resultDto.toString() = " + resultDto.toString());
        super.writeToClient(response, resultDto.toString());
    }

    @RequestMapping
    public String editMenu(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("edit method ....");
        PerResource perResource = this.perResourceService.get(id);
        model.addAttribute("perResource", perResource);
        return path_input_menu;
    }

    @RequestMapping
    public String addMenu(Long bizId, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("add method ....");
        PerResource perResource = new PerResource();
        if (bizId !=null) {
            PerResource parent = this.perResourceService.get(bizId);
            perResource.setParent(parent);
        }
        model.addAttribute("perResource", perResource);
        return path_input_menu;
    }

    @RequestMapping
    public String viewMenu(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("view method ....");
        PerResource perResource = this.perResourceService.get(id);
        model.addAttribute("perResource", perResource);
        return path_view_menu;
    }

    @RequestMapping
    public String editOperate(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("edit method ....");
        PerResource perResource = this.perResourceService.get(id);
        if (perResource == null) {

        }
        if (perResource.getParent() == null) {
            PerResource parent = new PerResource();
            parent.setId(0l);
            perResource.setParent(parent);
        }
        model.addAttribute("perResource", perResource);
        return path_input_operate;
    }

    @RequestMapping
    public String addOperate(Long bizId, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("add method ....");
        PerResource perResource = new PerResource();
        PerResource parent = null;
        if (bizId != 0l) {
            parent = this.perResourceService.get(bizId);
        } else {
            parent = new PerResource();
            parent.setId(0l);
        }
        perResource.setParent(parent);
        model.addAttribute("perResource", perResource);
        return path_input_operate;
    }

    @RequestMapping
    public String viewOperate(Long id, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("view method ....");
        PerResource perResource = this.perResourceService.get(id);
        model.addAttribute("perResource", perResource);
        return path_view_menu;
    }
    @RequestMapping
    public String search(Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("search method ....");
        return path_search;
    }

    @ResponseBody
    @RequestMapping
    @DateTimeFormat
    public void save(PerResource perResource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        //before
        perResource.setCode(MySecurityConstants.ROLE_USER);
        System.out.println("save method ....");
        MessageDto messageDto = new MessageDto();
        try {
            if (perResource.getId() != null) {
                this.perResourceService.update(perResource);
                super.setMessageDto(messageDto, MessageDefined.update_success_info);
            } else {
                this.perResourceService.save(perResource);
                super.setMessageDto(messageDto, MessageDefined.save_success_info);
            }
        } catch (Exception e) {
            messageDto.setSuccess(false);
            super.setMessageDto(messageDto, MessageDefined.sys_error_info);
            e.printStackTrace();
        }
        super.writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void delete(String ids, HttpServletRequest request, HttpServletResponse response) throws IOException {
        MessageDto messageDto = new MessageDto();
        try {
            Long id = Long.valueOf(ids);
//            this.perResourceService.deleteMoreCascade(id);
            super.setMessageDto(messageDto, MessageDefined.del_success_info);
        } catch (Exception e) {
            messageDto.setSuccess(false);
            super.setMessageDto(messageDto, MessageDefined.sys_error_info);
            e.printStackTrace();
        }
        super.writeToClient(response, messageDto.toString());
    }

    @ResponseBody
    @RequestMapping
    protected void tree(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Criterion> criterions = new ArrayList<Criterion>();
        criterions.add(Restrictions.eq("type", PerResourceType.MENU.getValue()));
        List<PerResource> entitys = this.perResourceService.listByCriteria(criterions);
        List<TreeModel> treeModels = new ArrayList<TreeModel>();
        for (PerResource entity : entitys) {
            TreeModel treeModel = new TreeModel();
            treeModel.setId(entity.getId());
            treeModel.setPid(entity.getParent() == null ? null : entity.getParent().getId());
            treeModel.setText(entity.getName());
            treeModels.add(treeModel);
        }
        treeModels = TreeUtils.generateTree(treeModels);
        String results = JsonUtil.transformObjectToString(treeModels);
        super.writeToClient(response, results);
    }

    @ResponseBody
    @RequestMapping
    protected void sysMenuTree(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Criterion> criterions = new ArrayList<Criterion>();
        criterions.add(Restrictions.eq("type", PerResourceType.MENU.getValue()));
        List<PerResource> entitys = this.perResourceService.listByCriteria(criterions);
        List<TreeModel> treeModels = new ArrayList<TreeModel>();
        for (PerResource entity : entitys) {
            TreeModel treeModel = new TreeModel();
            treeModel.setId(entity.getId());
            treeModel.setPid(entity.getParent() == null ? null : entity.getParent().getId());
            treeModel.setText(entity.getName());
            Map<String, String> map = new HashMap<String, String>();
            map.put("url",entity.getUrl());
            treeModel.setAttributes(map);
            treeModels.add(treeModel);
        }
        treeModels = TreeUtils.generateTree(treeModels);
        String results = JsonUtil.transformObjectToString(treeModels);
        super.writeToClient(response, results);
    }
}
